import { ipcMain, BrowserView, BrowserWindow } from 'electron';
import { join } from 'path';
import { readFileSync } from 'fs';
import { createHash } from 'crypto';
import Store from 'electron-store';
const store = new Store<{ key: String; value: any }>();

// 缩小
function minimize() {
  BrowserWindow.getFocusedWindow()?.minimize();
}
// 放大
function maximize() {
  BrowserWindow.getFocusedWindow()?.maximize();
}

// 正常化
function unmaximize() {
  BrowserWindow.getFocusedWindow()?.unmaximize();
}

// 关闭
function close() {
  BrowserWindow.getFocusedWindow()?.close();
}
/**
 * 主线程监听渲染线程发送的通讯
 */
// 缩小
ipcMain.on('windows:minimize', minimize);
// 放大
ipcMain.on('windows:maximize', maximize);
// 正常化
ipcMain.on('windows:unmaximize', unmaximize);
// 关闭
ipcMain.on('windows:close', close);

// setStore
ipcMain.on('store:setValue', (_, key, value) => {
  store.set(key, value);
});

// getStore
ipcMain.on('store:getValue', (_, key) => {
  _.returnValue = store.get(key) || '';
});

// clear
ipcMain.on('store:clear', (_) => {
  const value = store.get('account');
  store.clear();
  store.set('account', value);
});

let browserView: BrowserView | null = null;
ipcMain.on('close-browser-view', () => {
  browserView?.webContents?.close();
});

ipcMain.on('create-browser-view', async (_event, arg) => {
  const focusWindow = BrowserWindow.getFocusedWindow();
  if (!focusWindow) return;
  const partition = 'persist:' + arg.persist;
  browserView = new BrowserView({
    webPreferences: {
      allowRunningInsecureContent: true, // 允许加载不安全的内容
      nodeIntegration: true,
      preload: join(__dirname, 'whatsapp_injection.js'), // 指定预加载脚本的路径
      partition: partition, // 使用 'persist:' 前缀可以使分区在应用的多次启动间保持一致
      // ...其他选项
    },
  });
  const webContents = browserView.webContents;
  // 获取根据 partition 创建的 session
  // const customSession = session.fromPartition(partition);

  /*******拦截逻辑********/
  /*拦截请求*/
  // const filter = {
  //   urls: ['https://web.whatsapp.com/app.*.js'], // 替换为实际的脚本 URL
  // };
  // customSession.webRequest.onBeforeRequest(
  //   filter,
  //   async (details, callback) => {
  //     if (details.url.includes('https://web.whatsapp.com/app.')) {
  //       let res = await fetch(details.url);
  //       let responseText = await res.text();
  //       //执行替换操作
  //       const newResponseBody = responseText.replace(
  //         't.sendTextMsgToChat=function(){return G.apply(this,arguments)};',
  //         `t.sendTextMsgToChat=async function(){try{arguments[1]=await window.WA.translation(arguments[1],'en');return G.apply(this,arguments);}catch(error){alert("Error: "+(error.message||'Unknown error'));}};`
  //       );

  //       // 中断请求
  //       await callback({ cancel: true });

  //       // 注入代码
  //       await webContents
  //         .executeJavaScript(newResponseBody)
  //         .then((_r) => {
  //           console.log('发送实时翻译注入成功');
  //         })
  //         .catch((err) => {
  //           console.log('发送实时翻译注入失败:' + err);
  //         });
  //     } else {
  //       callback({});
  //     }
  //   }
  // );

  focusWindow.setBrowserView(browserView);
  browserView.setAutoResize({ width: true, height: true });
  const winSize = focusWindow.getSize();
  browserView.setBounds({
    x: 280,
    y: 40,
    width: winSize[0] - 300,
    height: winSize[1] - 50,
  });
  // webContents.openDevTools();
  webContents.setUserAgent(
    `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36`
  );

  webContents.on('did-finish-load', async () => {
    stopLoading();
    await webContents.executeJavaScript(
      readFileSync(join(__dirname, '../inject/jquery.js'), 'utf-8')
    );
    await webContents.insertCSS(
      readFileSync(join(__dirname, '../inject/css.css'), 'utf-8')
    );
    await webContents.executeJavaScript(
      readFileSync(join(__dirname, '../inject/translation.js'), 'utf-8')
    );
    await webContents.executeJavaScript(
      readFileSync(join(__dirname, '../inject/Injected.js'), 'utf-8')
    );
    webContents.executeJavaScript(`WA.waitForElement("[data-icon='search']")`);
  });

  await webContents.loadURL('https://web.whatsapp.com');
});

ipcMain.on('pageLoadFinish', async (_event, avator) => {
  if (!browserView) return;
  const userInfo = { username: '', avator: '', userId: '' };
  userInfo.avator = avator;
  await browserView.webContents.executeJavaScript(`window.injected()`);
  userInfo.username = await browserView.webContents.executeJavaScript(
    `window?.Store?.Conn?.serialize()?.pushname || ''`
  );
  userInfo.userId = await browserView.webContents.executeJavaScript(
    `window?.Store?.User?.getMeUser()?.user || ''`
  );
  BrowserWindow.getFocusedWindow()?.webContents.send('userInfo', userInfo);
});

// 停止加载
function stopLoading() {
  BrowserWindow.getFocusedWindow()?.webContents.send('stop-loading');
}

/*
    todo******以下方法只需要在主进程要注册一次**********
*/
//todo 翻译方法 需要做缓存处理,暂时没有做缓存,用map或者本地存储做,其中的Authorization是登录之后的Token
// 创建一个新的 Map 对象来存储缓存的翻译
// const translationCache = new Map();

ipcMain.handle('translation', async (_event, args) => {
  const cacheKey = generateCacheKey(args.text, args.targetLanguage);
  if (store.has(cacheKey)) {
    return Promise.resolve(store.get(cacheKey));
  }
  try {
    const response = await (
      await fetch('https://chat.miye009.com/api/v1/cust/message/translation', {
        method: 'POST',
        headers: {
          Authorization: store.get('chatToken'),
        },
        body: JSON.stringify({
          text: args.text,
          targetLanguage: args.targetLanguage,
        }),
      })
    ).json();

    if (response.code === 200) {
      store.set(cacheKey, response.data.translations);
      return response.data.translations;
    } else {
      if (response.message.indexOf('Bad language pair: {0}') > -1) {
        store.set(cacheKey, args.text);
        return args.text;
      }
      throw new Error(response.message);
    }
  } catch (error) {
    throw 'translation ERROR:' + error; // 这会使Promise变为rejected状态，并允许调用者访问完整的错误对象
  }
});

//todo 消息上报Authorization
ipcMain.handle('onMessage', (_event, args) => {
  console.log(args);
  console.log('消息上报:' + JSON.stringify(args));
});

function generateCacheKey(text: string, targetLanguage: string) {
  // 将文本和目标语言组合成一个字符串
  const key = `${text}_${targetLanguage}`;

  // 生成并返回MD5哈希
  return createHash('md5').update(key).digest('hex');
}
